<?php
class TBB_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
{
	public function preDispatch(Zend_Controller_Request_Abstract $request) {
		$acl = new TBB_Acl();
				
		// customer can have account or have no account
		$roles = array();
		$auth = Zend_Auth::getInstance();
		
		// bug here, comment this if block to enable jquery capability T____T
		if($auth->hasIdentity()) {
			$identity = $auth->getIdentity();
			$username = $identity->username;
			$userModel = new TBB_Model_Users();
			$userID = $userModel->getUserIDByUsername($username);		
			$roles = $userModel->getRolesOfUser($userID);	
		}
		
		// get module, controller and action names
		$module = $request->module;		
		$controller = $request->controller;
		$action = $request->action;		
		$resource = $module . ':' . $controller;

		if(!$acl->has($resource)) {
			$resource = $module;
		}

		if(empty($roles)) {
			$roles[] = array('role_name' => 'customer');
		}
		
		$allowed = false;
		foreach($roles as $role) {
			$allowed = $acl->isAllowed($role['role_name'], $resource, $action);
			if($allowed) {
				if($role['role_name'] == 'admin') {
					break; // important break			
				}
			}		
		} // end foreach
		
		// if the user hasn't logged in, send them to 'noauth' page.
		if(!$allowed) {			
			$request->setModuleName($module)->setControllerName('error')->setActionName('noauth');						
		}
	}
}